<?php

class DB_ACCESS extends ORM_Table {
    static protected $table_name = 'access';
    static public function getTableName($params = null) {
        //$table_name = self::$table_name.substr($params['article_type_id'], 0, 1);
        return self::$table_name;
    }

    /**
     * 获取插入sql语句
     * @param <type> $uhash
     * @return <type>
     */
    static public function insertSql($uhash) {
       if(!empty($uhash)){
            $acc    = self::getAccessObject($uhash);
            return $acc->getSqlString();
       }
    }
    /**
     * 获取表类
     * @param <type> $uhash
     * @return DB_ACCESS
     */
    static public function getAccessObject($uhash) {
        if(!empty($uhash)){
            if(empty($_SESSION['user']['id'])) {
                $uid    = 0;
            }else{
                $uid    = $_SESSION['user']['id'];
            }
            $ip = getIp();
            $referer    = getReferer();
            $host   = Common::pregDomain($referer);
            $acc    = new DB_ACCESS();
            $acc->setUhash($uhash);
            $acc->setIp(getIp());
            $acc->setUid($uid);
            $acc->setCreated(time());
            $acc->setHost($host);
            $acc->setReferer($referer);
            $acc->setAgent($_SERVER['HTTP_USER_AGENT']);
            return $acc;
       }else{
           return new DB_ACCESS();
       }
    }
    
    static public function writeAccess($uhash) {
        
        if(!empty($uhash)){
            if(empty($_SESSION['user']['id'])) {
                $uid    = 0;
            }else{
                $uid    = $_SESSION['user']['id'];
            }
            
            $ip = getIp();
            $referer    = getReferer();
            $host   = Common::pregDomain($referer);
            
            $acc    = new DB_ACCESS();
            $acc->setUhash($uhash);
            $acc->setIp(getIp());
            $acc->setUid($uid);
            $acc->setCreated(time());
            $acc->setHost($host);
            $acc->setReferer($referer);
            $acc->setAgent($_SERVER['HTTP_USER_AGENT']);
            $acc->save();
        }
        return $acc;
    }

    static function getPv($uhash=null, $start, $end){
        if(empty($uhash)) {
            $where  = "created >=$start and created<$end) ";
        }else{
            $where  = "(`uhash` = '$uhash' and created >=$start and created<$end) ";
        }
        $total  = DAO_Finder::findCount(DB_ACCESS, $where);
        if(empty($total)) {
            $total  = 0;
        }
        return $total;
    }
}

